#!coding=utf-8
from django.conf import settings 
from xml.etree import ElementTree
from django.http import HttpResponse
import hashlib
from weixin.api import comprocs

def callback(request):  
    """
    微信的回调信息
    """
    if getattr(settings,'DEBUG') == False:
        signature = request.GET.get("signature", None)
        timestamp = request.GET.get("timestamp", None)
        nonce = request.GET.get("nonce", None)
        echoStr = request.GET.get("echostr", None)
        token = getattr(settings,'WEIXIN_TOKEN')  
        tmpList = [token, timestamp, nonce]  
        tmpList.sort()  
        tmpstr = "%s%s%s" % tuple(tmpList)  
        tmpstr = hashlib.sha1(tmpstr).hexdigest()
        if tmpstr != signature: 
            return HttpResponse(u'您的访问请求与验证信息不符合')
    
    msg = {}
    
    if request.body == "":
        echoStr = request.GET.get("echostr", None)
        return HttpResponse(echoStr)
    
    xml_elem = ElementTree.fromstring(request.body)
    
    
    if xml_elem.tag == 'xml':
        for child in xml_elem:
            msg[child.tag] = child.text
    
    msgType=msg.get("MsgType")
    proc_function = getattr(comprocs,"proc_%s"%msgType)
        
    if callable(proc_function):
        return proc_function(msg)
    else:
        return HttpResponse("XML ERROR")
    
#     
#     if msg['MsgType'] in 'text':
#         print 'text message'
#         return HttpResponse(process_text_msg(msg))
#     
#     elif msg['MsgType'] == 'location':
#         return HttpResponse(process_location_msg(msg))
#     
#     elif msg['MsgType'] == 'event':
#         if msg['Event'] == 'subscribe':
#             print "subscribe"
#             return HttpResponse(process_subscribe_event(msg))
#         elif msg['Event'] == 'unsubscribe':
# #             print 'unsubscribe event'
#             return HttpResponse(process_unsubscribe_event(msg)) 
#         elif msg['Event'] == 'SCAN':
# #             print 'already subscribed'
#             return HttpResponse(process_scan_event(msg))  
#         elif msg['Event'] == 'LOCATION':
#             print 'LOCATION event'
#             return HttpResponse(process_location_event(msg)) 
#         elif msg['Event'] == 'CLICK':
# #             print 'click evevt'
#             return HttpResponse(process_click_event(msg)) 
#         elif msg['Event'] == 'VIEW':
# #             print 'view event'   
#             return HttpResponse(process_view_event(msg)) 
#     elif msg['MsgType'] == 'image':
#         return HttpResponse(process_image_msg(msg))
#            
#     elif msg['MsgType'] == 'voice' and 'Recognition' not in msg:
#         return HttpResponse(process_voice_msg(msg))
#     
#     elif msg['MsgType'] == 'voice' :
#         print 'voice recognition event'
#     
#     elif msg['MsgType'] == 'video':
#         return HttpResponse(process_video_msg(msg))
#     
#     elif msg['MsgType'] == 'link':
#         return HttpResponse(process_link_msg(msg))
#         
        



    
        
